package com.tbq.game.service.dao

import android.util.Log
import com.alibaba.fastjson.JSON
import com.tbq.game.service.utils.Md5Util
import java.net.URLEncoder
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.*

open class BaseDao {
    val KEY = "tu3hi48w01"
    val CODE = "1000"
    val FORMAT = "json"
    /**
     * 插入接口数据
     *
     * @param params
     * @param strParams
     */
    open fun insertInterfaceData(data: MutableMap<String, Any>?, vararg strParams: String): MutableMap<String, Any> {
        val params = data ?: mutableMapOf()
        val time = (Date(System.currentTimeMillis()).time).toString()
        params.put("code", CODE)
        params.put("time", time)
        params.put("format", FORMAT)
        val temParams = arrayOfNulls<String>(strParams.size + 3)

        temParams[0] = CODE
        temParams[1] = KEY
        temParams[2] = time

        for (i in 3 until temParams.size) {
            temParams[i] = strParams[i - 3]
        }
        params.put("sign", createMd5(temParams))
        Log.e("insertInterfaceData", "${JSON.toJSONString(temParams)}")
        return params
    }

    /**
     * 获取指定格式的当前时间
     */
    val FORMAT_TIME = "yyyy-MM-dd HH:mm:ss"

    fun getTime(): String {
        return SimpleDateFormat(FORMAT_TIME).format(Date(System.currentTimeMillis()))
    }

    fun createMd5(strParams: Array<String?>): String {
        val strBuffer = StringBuffer()

        for (i in strParams.indices) {
            strBuffer.append(strParams[i] + "")
        }
        return Md5Util.md5(strBuffer.toString())
    }

    fun toURLEncoded(paramString: String?): String {
        if (paramString == null || paramString == "") {
            Log.e("URL_ENCODE", "toURLEncoded error:" + paramString!!)
            return ""
        }

        try {
            var str = String(paramString.toByteArray(), Charset.forName("UTF-8"))
            str = URLEncoder.encode(str, "UTF-8")
            return str
        } catch (localException: Exception) {
            Log.e("toURLEncoded error:" + paramString, localException.toString())
        }

        return ""
    }
}